package com.lzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzy.api.feign.FileMicroServiceFeign;
import com.lzy.base.BaseInfoProperties;
import com.lzy.enums.Sex;
import com.lzy.grace.result.GraceJSONResult;
import com.lzy.mapper.UsersMapper;
import com.lzy.pojo.Users;
import com.lzy.service.UsersService;
import com.lzy.utils.DesensitizationUtil;
import com.lzy.utils.JsonUtils;
import com.lzy.utils.LocalDateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lzy
 * @since 2025-08-26
 */
@Service
public class UsersServiceImpl extends BaseInfoProperties implements UsersService {


    private static final String USER_FACE = "https://picx.zhimg.com/v2-d6f44389971daab7e688e5b37046e4e4_720w.jpg?source=172ae18b";

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private FileMicroServiceFeign fileMicroServiceFeign;

    @Override
    public Users queryMobileExist(String mobile) {
        return usersMapper.selectOne(
                new QueryWrapper<Users>()
                        .eq("mobile",mobile));
    }

    @Transactional
    @Override
    public Users createUsers(String mobile,String nickname) {
        Users user = new Users();

        user.setMobile(mobile);

        String uuid = UUID.randomUUID().toString();
        String uuidStr[] = uuid.split("-");
        String wechatNum = "wx" + uuidStr[0] + uuidStr[1];
        user.setWechatNum(wechatNum);

        // FIXME
        // 生成二维码
        GraceJSONResult jsonResult = fileMicroServiceFeign.generateorQrCode(wechatNum,"temp");
        Object data = jsonResult.getData();
        String json = JsonUtils.objectToJson(data);
        String imageQrCodeurl = JsonUtils.jsonToPojo(json, String.class);
        user.setWechatNumImg(imageQrCodeurl);

        if(StringUtils.isBlank(nickname)){
            nickname = DesensitizationUtil.commonDisplay(mobile);
        }
        user.setNickname(nickname);
        user.setRealName("张三");
        user.setSex(Sex.man.type);
        user.setFace(USER_FACE);
        user.setFriendCircleBg(USER_FACE);
        user.setEmail("");

        user.setBirthday(LocalDateUtils
                .parseLocalDate("2004-05-30",LocalDateUtils.DATE_PATTERN));

        user.setCountry("中国");
        user.setProvince("");
        user.setCity("");
        user.setCountry("");

        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());

        usersMapper.insert(user);
        return user;
    }
}
